import axios from 'axios';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
// let userStore;
const request = axios.create({
  baseURL: "https://ai.idimage.cn",
  timeout: 10000
});

let isRefreshing = false;
const retryQueue = [];

// 请求拦截器
// request.interceptors.request.use(
//   (config) => {
//     // ✅ 每次请求都获取最新 Store 实例
//     const userStore = useUserStore();
//     const token = userStore.token || localStorage.getItem('ACCESS_TOKEN');
//     if (token) {
//       config.headers['Authorization'] = token;
//     }
//     return config;
//   },
//   (error) => Promise.reject(error)
// );

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 如果是刷新 token 的请求，不添加 token 头
    if (config.url === '/api/kingsha/external/refresh/token') {
      return config;
    }
    
    // 其他请求添加 token 头
    const userStore = useUserStore();
    const token = userStore.token || localStorage.getItem('ACCESS_TOKEN');
    if (token) {
      config.headers['Authorization'] = token;
    }
    return config;
  },
  (error) => Promise.reject(error)
);


request.interceptors.response.use(
  (response) => {
    const data = response.data;
    
    // 检查业务状态码
    if (data.status !== 200) {
      // 弹窗提示 message
      ElMessage.error(data.message || '请求失败');
      
      if (data.status === 102) {
        return handleTokenExpired(response.config);
      }
      return Promise.reject(new Error(data.message || '请求失败'));
    }
    
    return response;
  },
  async (error) => {
    const businessStatus = error.response?.data?.status;
    const errorMessage = error.response?.data?.message;

    // 处理 Token 过期
    if (businessStatus === 102 && !error.config._retry) {
      return await handleTokenExpired(error.config);
    }

    // 显示通用错误提示
    // ElMessage.error(errorMessage || '网络连接失败');
    return Promise.reject(error);
  }
);

// export async function handleTokenExpired(config = null) {
//   if (isRefreshing) {
//     return new Promise(resolve => retryQueue.push(resolve));
//   }

//   isRefreshing = true;

//   try {
//     const newToken = await refreshAccessToken();
//     console.log('刷新后的新 Token:', newToken);
//     config.headers['Authorization'] = newToken;
//     config._retry = true;

//     retryQueue.forEach(cb => cb());
//     retryQueue.length = 0;
//     isRefreshing = false;
//     return request(config);
//   } catch (error) {
//     isRefreshing = false;
//     // ✅ 根据错误信息判断是否需要重置
//     if (error.message.includes('Refresh Token 已过期') || error.message.includes('Refresh Token 不存在')){

//       ElMessage.error('登录已过期，请重新打开界面');

//       const userStore = useUserStore();
//       userStore.setToken(null);
//       userStore.setRefreshToken(null);
//       localStorage.removeItem('ACCESS_TOKEN');
//       localStorage.removeItem('REFRESH_TOKEN');
//     }
//     return Promise.reject(error);
//   }
// }

export async function handleTokenExpired(config = null) {
  if (isRefreshing) {
    // 如果已经在刷新中，将请求加入队列
    if (config) {
      return new Promise(resolve => retryQueue.push(() => resolve(request(config))));
    }
    return new Promise(resolve => retryQueue.push(resolve));
  }

  isRefreshing = true;

  try {
    const newToken = await refreshAccessToken();
    console.log('刷新后的新 Token:', newToken);
    
    // 如果传入了 config，更新其 headers 并重试请求
    if (config) {
      config.headers['Authorization'] = newToken;
      config._retry = true;
      
      retryQueue.forEach(cb => cb());
      retryQueue.length = 0;
      isRefreshing = false;
      return request(config);
    }
    
    // 没有传入 config，只刷新 token
    retryQueue.forEach(cb => cb());
    retryQueue.length = 0;
    isRefreshing = false;
    return newToken;
  } catch (error) {
    isRefreshing = false;
    // 处理错误...
    return Promise.reject(error);
  }
}

export async function refreshAccessToken() {
  const userStore = useUserStore();
  try {
    
    const refreshToken = userStore.refreshToken || localStorage.getItem('REFRESH_TOKEN');
    console.log('当前使用的 refreshToken:', refreshToken);
    if (!refreshToken) throw new Error('Refresh Token 不存在');
    // 创建一个新的 axios 实例，避免拦截器干扰
    const refreshRequest = axios.create({
      baseURL: "https://ai.idimage.cn",
      timeout: 10000
    });
    const response = await refreshRequest.post(
      '/api/kingsha/external/refresh/token', // 相对路径
      {},
      {
        headers: { 'Authorization': refreshToken }
      }
    );
    if (response.data.status === 200) {
      const { token, refresh_token, name, username } = response.data.result;
      userStore.setToken(null);
      userStore.setRefreshToken(null);
      localStorage.removeItem('ACCESS_TOKEN');
      localStorage.removeItem('REFRESH_TOKEN');
      userStore.setToken(token);
      userStore.setRefreshToken(refresh_token);
      userStore.setUserInfo({ name, username });
      localStorage.setItem('ACCESS_TOKEN', token);
      localStorage.setItem('REFRESH_TOKEN', refresh_token);
      return token;
    } else {
      throw new Error('刷新 Token 失败');
    }
  } catch (error) {
    ElMessage.error('刷新 Token 失败，请重新进入页面');
    const userStore = useUserStore();
    userStore.setToken(null);
    userStore.setRefreshToken(null);
    localStorage.removeItem('ACCESS_TOKEN');
    localStorage.removeItem('REFRESH_TOKEN');
    return Promise.reject(error);
  }
}
export default request;